//
//  XLMessageView.m
//  industry
//
//  Created by xl on 2020/11/12.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLMessageView.h"
#import "XLMessageViewProtocol.h"
#import "XLMessageCustomView.h"
#import "XLMessageAdapter.h"
#import "XLMessageModel.h"
#import "XLMessagePresenterProtocol.h"
#import "YQMessageEditBottomView.h"

@interface XLMessageView () <XLMessageViewProtocol, RPTaggedNavViewDelegate, XLAdapterDelegate>

@property (nonatomic, strong) XLMessageCustomView *customView;
@property (nonatomic, strong) XLTableView *tableView;
@property (nonatomic, strong) XLMessageAdapter *adapter;
@property (nonatomic, strong) YQMessageEditBottomView *editBottomView;

@property (nonatomic, assign) BOOL isAllSelect;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger type;//0未读 1已读

@property (nonatomic, strong) AUToast *toastLoad;
@property (nonatomic, strong)  AUNetErrorView *errorView;


@end
@implementation XLMessageView

- (void)dealloc {
    XLLog(@"XLMessageView dealloc");
}

#pragma mark - XLMessageViewProtocol
- (void)buildView {
    [self addSubview:self.customView];
    [self addSubview:self.tableView];
    [_customView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(140 + STATUSBAR_HEIGHT);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customView.mas_bottom);
        make.left.bottom.right.equalTo(self);
    }];

    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
         STRONGSELF
        strongSelf.page = 1;
        XLSend(strongSelf.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:strongSelf.page searchStr:nil);
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        STRONGSELF
        strongSelf.page ++;
        NSString * str = [strongSelf.customView.searchBarView getSearchText];
        if (ISEmptyString(str)) {
            str = nil;
        }
        XLSend(strongSelf.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:strongSelf.page searchStr:str);
    }];
    [self showNoResultView:YES];
    //开始请求数据
    [XLUserData sharedXLUserData].isMessageFirst = NO;
    XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:1 searchStr:nil);
}

- (void)refreshTableView:(NSArray *)dataArr noData:(BOOL)noData {
    [self endRefresh];
    if (noData) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    NSMutableArray *currenArray = [[NSMutableArray alloc] init];
    if (_page != 1) {
        [currenArray addObjectsFromArray:self.adapter.getAdapterArray];
    }
    [currenArray addObjectsFromArray:dataArr];
    if (currenArray.count > 0) {
        [self showNoResultView:NO];
    } else {
        [self showNoResultView:YES];
    }
    [self.adapter setAdapterArray:currenArray];
    [self.tableView reloadData];
}

- (void)requestServerError:(NSError *)error networkReachabilityStatus:(XLNetworkReachabilityStatus)status {
    [self endRefresh];
    if (_adapter.getAdapterArray.count == 0) {
        if (!_errorView || !_errorView.superview) {
            [self showNoResultView:YES];
        }
        _errorView.iconImageView.image = XLIMAGE(@"noxx");
        _errorView.infoTitle = @"咦，出错了~";
    }
}

- (void)beginSearchBar:(NSString *)text {
    
    [_adapter setAdapterArray:nil];
    [_tableView reloadData];
    [self.tableView.mj_footer resetNoMoreData];
    XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:1 searchStr:text);
    
}

- (void)refreshNewRequest {
    if ([XLUserData sharedXLUserData].isMessageFirst) {
        [XLUserData sharedXLUserData].isMessageFirst = NO;
        
        [_customView.segment selectingOneTagWithIndex:0];//重置初始位置
        self.page = 1;
        self.type = 0;
        _adapter.isRead = NO;
        
        XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:1 searchStr:nil);
    }
}

//正在加载中的动画
- (void)showLoadingAnimalWithTitle:(NSString *)title {
    self.toastLoad = [XLToast showLoadingTitle:title superView:self];
}

- (void)hideLoadingAnimal {
    if (self.toastLoad) {
        [self.toastLoad dismissToast];
    }
}

- (void)refreshTableViewData {
    [_tableView.mj_header beginRefreshing];
}

#pragma mark - XLAdapterDelegate
- (void)didSelectCellData:(id)cellData {
    XLSend(self.baseController.presenter, XLMessagePresenterProtocol, handleCellData:cellData isRead:_adapter.isRead);
}

- (void)deleteCellData:(id)cellData indexPath:(NSIndexPath *)indexPath {
    XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestDeleteMessage:cellData);
}

#pragma mark - RPTaggedNavViewDelegate
- (void)haveSelectedIndex:(NSInteger)index {
    if (index == self.type) {
        return;
    }
    [self.customView.searchBarView clearSearchBar];
    [_adapter setAdapterArray:nil];
    [_tableView reloadData];
    self.type = index;
    _adapter.isRead = index;
    [self.tableView.mj_footer resetNoMoreData];
    XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestMessageList:self.type page:1 searchStr:nil);
}

#pragma mark - UIButton
//点击删除
- (void)clickDelete {
    _isAllSelect = NO;
    [_customView changeEditStatus:NO];
    [self hiddenBottomView];
    [self.tableView setEditing:NO animated:YES];
    
    NSMutableArray *temArr = [NSMutableArray array];
    for (XLMessageModel *model in _adapter.getAdapterArray) {
        if (model.isSelect) {
            [temArr addObject:model];
        }
    }
    if (temArr.count > 0) {
        XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestDeleteMessages:temArr);
    }
}

//点击编辑
- (void)clickEdit {
    [_customView changeEditStatus:YES];
    [self showBottomView];
    [_tableView setEditing:YES animated:YES];
    [_tableView reloadData];
}

/// 点击已读
- (void)clickRead {
    _isAllSelect = NO;
    [_customView changeEditStatus:NO];
    [self hiddenBottomView];
    [self.tableView setEditing:NO animated:YES];
    
    NSMutableArray *temArr = [NSMutableArray array];
    for (XLMessageModel *model in _adapter.getAdapterArray) {
        if (model.isSelect) {
            [temArr addObject:model];
        }
    }
    if (temArr.count > 0) {
        XLSend(self.baseController.presenter, XLMessagePresenterProtocol, requestAlreadyReadMessages:temArr);
    }
}


/// 点击关闭
- (void)clickClose {
    [_customView changeEditStatus:NO];
    [self hiddenBottomView];
    [_tableView setEditing:NO animated:YES];
    [_tableView reloadData];
}

//选择全部
- (void)clickSelectAll {
    _isAllSelect = !_isAllSelect;
    if (_isAllSelect) {
        [self.adapter.getAdapterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            XLMessageModel *model = (XLMessageModel *)obj;
            model.isSelect = YES;
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:idx] animated:NO scrollPosition:UITableViewScrollPositionNone];
        }];
    } else {
        [self.adapter.getAdapterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            XLMessageModel *model = (XLMessageModel *)obj;
            model.isSelect = NO;
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:idx] animated:NO];
        }];
    }
}

#pragma mark - Private
- (void)endTableViewEdit {
    //回复数据状态
    [self.adapter.getAdapterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XLMessageModel *model = (XLMessageModel *)obj;
        model.isSelect = NO;
    }];
}

- (void)showNoResultView:(BOOL)show
{
    if (show) {
        if(!_errorView) {
            [self.adapter setAdapterArray:nil];//清除数据，避免下拉仍然可见旧数据。
            [UIView animateWithDuration:0 animations:^{
                [self.tableView reloadData];
            }];
            [self.tableView addSubview:self.errorView];
            
        } else {
            _errorView.iconImageView.image = XLIMAGE(@"noxx");
            _errorView.infoTitle = @"暂无新消息";
        }
    } else {
        if (_errorView) {
            [_errorView dismiss];
            _errorView = nil;
        }
    }
}

-(void)showBottomView{
    if (self.editBottomView == nil) {
        
        YQMessageEditBottomView * editBottomView = [[YQMessageEditBottomView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH , 52)];
        WEAKSELF
        [editBottomView setDelteButtonClickBlock:^{
            [weakSelf clickDelete];
        }];
        [editBottomView setReadButtonClickBlock:^{
            [weakSelf clickRead];
        }];
        self.editBottomView = editBottomView;
        [editBottomView showWithType:self.type];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        [window addSubview:editBottomView];
        
        [UIView animateWithDuration:0.5 animations:^{
                  
            [editBottomView setFrame:CGRectMake(0, SCREEN_HEIGHT - 52 - SAFEAREA_BOTTOM_HEIGHT, SCREEN_WIDTH , 52 + SAFEAREA_BOTTOM_HEIGHT)];
        }];
        
    }
}

-(void)hiddenBottomView{
    
    [UIView animateWithDuration:0.5 animations:^{
        [self.editBottomView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH , 52 + SAFEAREA_BOTTOM_HEIGHT)];
    } completion:^(BOOL finished) {
        [self.editBottomView removeFromSuperview];
        self.editBottomView = nil;
    }];
    
    
}

#pragma mark - MJrefersh 相关
- (void)endRefresh {
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    if (self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - sette/getter
- (XLMessageCustomView *)customView {
    if (!_customView) {
        _customView = [[XLMessageCustomView alloc] init];
        WEAKSELF
        [_customView setSegmentSelectBlock:^(NSInteger index) {
            [weakSelf haveSelectedIndex:index];
        }];
        [_customView.searchBarView setTextFieldChangeCallBack:^(NSString * _Nonnull text) {
            [weakSelf beginSearchBar:text];
        }];
        
        [_customView setCloseButtonClickBlock:^(XLButton * _Nonnull button) {
            [weakSelf clickClose];
        }];
        [_customView setSelectButtonClickBlock:^(XLButton * _Nonnull button) {
            [weakSelf clickSelectAll];
        }];
        [_customView setEditButtonClickBlock:^(XLButton * _Nonnull button) {
            [weakSelf clickEdit];
        }];
        


    }
    return _customView;
}

- (XLTableView *)tableView {
    if (!_tableView) {
        _tableView = [[XLTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteBgColor];
        _tableView.allowsMultipleSelectionDuringEditing = YES;
        _tableView.delegate = self.adapter;
        _tableView.dataSource = self.adapter;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (XLMessageAdapter *)adapter {
    if (!_adapter) {
        _adapter = [[XLMessageAdapter alloc] init];
        _adapter.adapterDelegate = self;
    }
    return _adapter;
}

- (AUNetErrorView *)errorView {
    if (!_errorView) {
        _errorView = [[AUNetErrorView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATIONBAR_HEIGHT) style:AUNetErrorStyleIlustration type:AUNetErrorTypeEmpty target:nil action:nil];
        _errorView.iconImageView.image = XLIMAGE(@"noxx");
        _errorView.infoTitle = @"暂无新消息";
        _errorView.detailTitle = @"";
        _errorView.backgroundColor = [UIColor whiteBgColor];
        _errorView.infoLabel.textColor = [UIColor colorWithHex:0x9C9C9C];
        _errorView.infoLabel.font = [UIFont fontOfPingFangSCRegularWithSize:14];
        
    }
    return _errorView;
}

@end
